package win.itshen.cloud.shiro.common.shiro;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

public class ShiroSessionManager extends DefaultWebSessionManager {

	private static final String AUTHORIZATION = "X-Token";
	private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";

	/** 
	 * 获取session id
	 * 前后端分离将从请求头中获取jsesssionid
	 */
	@Override
	protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
		//获取请求头中X-Token中保存的sessionId
		String token = WebUtils.toHttp(request).getHeader(AUTHORIZATION);
		// 判断是否有值
		if (StringUtils.isNoneBlank(token)) {
			// 设置当前session状态
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, token);
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
			return token;
		}
		// 若header获取不到token则尝试从cookie中获取
		return super.getSessionId(request, response);
	}
}